package org.afei.ioc.listener;


import org.afei.ioc.bean.Person;
import org.afei.ioc.container.Container;
import org.afei.ioc.container.DefaultContainer;
import org.afei.ioc.util.ReflectionUtil;

import java.io.IOException;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author afei
 * @date 17-5-26.
 */
public class HotDeploymentListener {

    private WatchService watcher;

    public HotDeploymentListener(Path path)
            throws IOException {
        watcher = FileSystems.getDefault().newWatchService();
        path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
    }

    public static void main(String args[])
            throws IOException, InterruptedException {
        new HotDeploymentListener(Paths.get("/home/afei/work/codes/IoCContainer/src/main/java/org/afei/bean"))
                .handleEvents();
    }

    public void handleEvents()
            throws InterruptedException {
        while (true) {
            WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind kind = event.kind();

                if (kind == StandardWatchEventKinds.OVERFLOW) {//事件可能lost or discarded
                    continue;
                }

                WatchEvent<Path> e = (WatchEvent<Path>) event;
                Path fileName = e.context();
                System.out.printf("Event %s has happened,which fileName is %s%n"
                        , kind.name(), fileName);

                //TODO:重新加载容器
                Map<String, Object> map = new HashMap<>();

                Container container = new DefaultContainer(map);
                Person person = (Person) container.getBean("person");
                Object result = ReflectionUtil.invoke(person, ReflectionUtil.getMethods(person)[0], "China");
                System.out.println(result.toString());
            }
            if (!key.reset()) {
                break;
            }
        }
    }

}
